package com.xingfly.inventory.model;

import com.xingfly.inventory.sdk.event.InventoryChangedEvent;
import com.xingfly.jpa.common.BaseEntity;
import lombok.*;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.time.LocalDateTime;

/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "t_inventory")
@EqualsAndHashCode(callSuper = true)
public class Inventory extends BaseEntity<InventoryId> {

    private String productId;

    private String productName;

    private int remains;

    private Boolean deleted;

    public static Inventory create(String productId, String productName) {
        Inventory inventory = Inventory.builder()
                .productId(productId)
                .productName(productName)
                .remains(0)
                .build();
        inventory.setId(new InventoryId());
        inventory.setCreateTime(LocalDateTime.now());
        return inventory;
    }

    public void decrease(int number) {
        this.remains = this.remains - number;
        registerEvent(new InventoryChangedEvent(productId, remains));
    }

    public void increase(int number) {
        this.remains = this.remains + number;
        registerEvent(new InventoryChangedEvent(productId, remains));
    }

    public void updateProductName(String newName) {
        this.productName = newName;
    }
}
